package com.yeming.tinyid.application.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @author yeming.gao
 * @Description: 请求过滤器；请求耗时记录
 * @date 2020/07/28 16:15
 */
@WebFilter(urlPatterns = "/*", filterName = "requestFilter")
public class RequestFilter implements Filter {

    private static final Logger LOGGER = LoggerFactory.getLogger(RequestFilter.class);

    @Override
    public void init(FilterConfig filterConfig) {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        StringBuilder params = new StringBuilder();
        Map<String, String[]> paramsMap = request.getParameterMap();
        if (paramsMap != null && !paramsMap.isEmpty()) {
            for (Map.Entry<String, String[]> entry : paramsMap.entrySet()) {
                params.append(entry.getKey()).append(":")
                        .append(StringUtils.arrayToDelimitedString(entry.getValue(), ","))
                        .append(";");
            }
        }
        long start = System.currentTimeMillis();


        try {
            filterChain.doFilter(request, response);
        } catch (ServletException | IOException e) {
            LOGGER.error("request filter error:", e);
        } finally {
            long cost = System.currentTimeMillis() - start;
            LOGGER.info("request filter path={}, cost={}, params={}", request.getServletPath(), cost, params);
        }
    }

    @Override
    public void destroy() {

    }
}
